package com.kitchen.dao;

import com.kitchen.entity.Order;
import com.kitchen.entity.OrderItem;
import com.kitchen.util.DatabaseUtil;

import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * 订单DAO类
 * 使用List和Map集合处理数据
 */
public class OrderDAO {
    
    /**
     * 创建订单
     */
    public Integer createOrder(Order order) {
        String sql = "INSERT INTO `order` (order_number, table_number, order_time, status, total_amount) VALUES (?, ?, ?, ?, ?)";
        
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        
        try {
            conn = DatabaseUtil.getConnection();
            conn.setAutoCommit(false); // 开启事务
            
            // 插入订单主表
            pstmt = conn.prepareStatement(sql, PreparedStatement.RETURN_GENERATED_KEYS);
            pstmt.setString(1, order.getOrderNumber());
            pstmt.setString(2, order.getTableNumber());
            pstmt.setTimestamp(3, Timestamp.valueOf(order.getOrderTime()));
            pstmt.setString(4, order.getStatus());
            pstmt.setBigDecimal(5, order.getTotalAmount());
            
            pstmt.executeUpdate();
            rs = pstmt.getGeneratedKeys();
            
            if (rs.next()) {
                Integer orderId = rs.getInt(1);
                
                // 插入订单明细
                insertOrderItems(conn, orderId, order.getItems());
                
                conn.commit();
                return orderId;
            }
            
            conn.rollback();
            return null;
        } catch (SQLException e) {
            try {
                if (conn != null) {
                    conn.rollback();
                }
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
            throw new RuntimeException("创建订单失败: " + e.getMessage(), e);
        } finally {
            DatabaseUtil.close(conn, pstmt, rs);
        }
    }
    
    /**
     * 插入订单明细
     */
    private void insertOrderItems(Connection conn, Integer orderId, List<OrderItem> items) throws SQLException {
        String sql = "INSERT INTO order_item (order_id, dish_id, quantity, price, status) VALUES (?, ?, ?, ?, ?)";
        
        try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
            for (OrderItem item : items) {
                pstmt.setInt(1, orderId);
                pstmt.setInt(2, item.getDishId());
                pstmt.setInt(3, item.getQuantity());
                pstmt.setBigDecimal(4, item.getPrice());
                pstmt.setString(5, item.getStatus());
                pstmt.addBatch();
            }
            pstmt.executeBatch();
        }
    }
    
    /**
     * 查询所有订单
     */
    public List<Order> findAll() {
        List<Order> orders = new ArrayList<>();
        String sql = "SELECT * FROM `order` ORDER BY order_time DESC";
        
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        
        try {
            conn = DatabaseUtil.getConnection();
            pstmt = conn.prepareStatement(sql);
            rs = pstmt.executeQuery();
            
            while (rs.next()) {
                Order order = mapResultSetToOrder(rs);
                // 加载订单明细
                order.setItems(findOrderItemsByOrderId(order.getOrderId()));
                orders.add(order);
            }
        } catch (SQLException e) {
            throw new RuntimeException("查询订单失败: " + e.getMessage(), e);
        } finally {
            DatabaseUtil.close(conn, pstmt, rs);
        }
        
        return orders;
    }
    
    /**
     * 根据ID查询订单
     */
    public Order findById(Integer orderId) {
        String sql = "SELECT * FROM `order` WHERE order_id = ?";
        
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        
        try {
            conn = DatabaseUtil.getConnection();
            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, orderId);
            rs = pstmt.executeQuery();
            
            if (rs.next()) {
                Order order = mapResultSetToOrder(rs);
                order.setItems(findOrderItemsByOrderId(orderId));
                return order;
            }
        } catch (SQLException e) {
            throw new RuntimeException("查询订单失败: " + e.getMessage(), e);
        } finally {
            DatabaseUtil.close(conn, pstmt, rs);
        }
        
        return null;
    }
    
    /**
     * 根据状态查询订单
     */
    public List<Order> findByStatus(String status) {
        List<Order> orders = new ArrayList<>();
        String sql = "SELECT * FROM `order` WHERE status = ? ORDER BY order_time DESC";
        
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        
        try {
            conn = DatabaseUtil.getConnection();
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, status);
            rs = pstmt.executeQuery();
            
            while (rs.next()) {
                Order order = mapResultSetToOrder(rs);
                order.setItems(findOrderItemsByOrderId(order.getOrderId()));
                orders.add(order);
            }
        } catch (SQLException e) {
            throw new RuntimeException("查询订单失败: " + e.getMessage(), e);
        } finally {
            DatabaseUtil.close(conn, pstmt, rs);
        }
        
        return orders;
    }
    
    /**
     * 分配厨师
     */
    public boolean assignChef(Integer orderId, Integer chefId) {
        String sql = "UPDATE `order` SET chef_id = ?, status = '制作中' WHERE order_id = ?";
        
        Connection conn = null;
        PreparedStatement pstmt = null;
        
        try {
            conn = DatabaseUtil.getConnection();
            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, chefId);
            pstmt.setInt(2, orderId);
            
            return pstmt.executeUpdate() > 0;
        } catch (SQLException e) {
            throw new RuntimeException("分配厨师失败: " + e.getMessage(), e);
        } finally {
            DatabaseUtil.close(conn, pstmt);
        }
    }
    
    /**
     * 完成订单
     */
    public boolean completeOrder(Integer orderId) {
        String sql = "UPDATE `order` SET status = '已完成', complete_time = ? WHERE order_id = ?";
        
        Connection conn = null;
        PreparedStatement pstmt = null;
        
        try {
            conn = DatabaseUtil.getConnection();
            pstmt = conn.prepareStatement(sql);
            pstmt.setTimestamp(1, Timestamp.valueOf(LocalDateTime.now()));
            pstmt.setInt(2, orderId);
            
            return pstmt.executeUpdate() > 0;
        } catch (SQLException e) {
            throw new RuntimeException("完成订单失败: " + e.getMessage(), e);
        } finally {
            DatabaseUtil.close(conn, pstmt);
        }
    }
    
    /**
     * 查询订单明细
     */
    private List<OrderItem> findOrderItemsByOrderId(Integer orderId) {
        List<OrderItem> items = new ArrayList<>();
        String sql = "SELECT oi.*, d.dish_name FROM order_item oi " +
                     "LEFT JOIN dish d ON oi.dish_id = d.dish_id " +
                     "WHERE oi.order_id = ?";
        
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        
        try {
            conn = DatabaseUtil.getConnection();
            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, orderId);
            rs = pstmt.executeQuery();
            
            while (rs.next()) {
                OrderItem item = new OrderItem();
                item.setItemId(rs.getInt("item_id"));
                item.setOrderId(rs.getInt("order_id"));
                item.setDishId(rs.getInt("dish_id"));
                item.setDishName(rs.getString("dish_name"));
                item.setQuantity(rs.getInt("quantity"));
                item.setPrice(rs.getBigDecimal("price"));
                item.setStatus(rs.getString("status"));
                items.add(item);
            }
        } catch (SQLException e) {
            throw new RuntimeException("查询订单明细失败: " + e.getMessage(), e);
        } finally {
            DatabaseUtil.close(conn, pstmt, rs);
        }
        
        return items;
    }
    
    private Order mapResultSetToOrder(ResultSet rs) throws SQLException {
        Order order = new Order();
        order.setOrderId(rs.getInt("order_id"));
        order.setOrderNumber(rs.getString("order_number"));
        order.setTableNumber(rs.getString("table_number"));
        if (rs.getTimestamp("order_time") != null) {
            order.setOrderTime(rs.getTimestamp("order_time").toLocalDateTime());
        }
        order.setStatus(rs.getString("status"));
        order.setTotalAmount(rs.getBigDecimal("total_amount"));
        int chefId = rs.getInt("chef_id");
        if (rs.wasNull()) {
            order.setChefId(null);
        } else {
            order.setChefId(chefId);
        }
        if (rs.getTimestamp("complete_time") != null) {
            order.setCompleteTime(rs.getTimestamp("complete_time").toLocalDateTime());
        }
        return order;
    }
}

